<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="updateVisible"
    title="导入脚本"
    width="800px"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="space-y-4">
      <!-- 脚本输入区域 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          脚本内容
        </label>
        <el-input
          v-model="scriptContent"
          type="textarea"
          :rows="12"
          placeholder="请粘贴Playwright脚本内容，或使用下方的文件上传功能"
          class="font-mono text-sm"
        />
      </div>

      <!-- 文件上传区域 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          或上传脚本文件
        </label>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          accept=".js,.ts,.jsonl,.json,.py"
          :on-change="handleFileChange"
          drag
        >
          <div class="text-center py-6">
            <el-icon class="text-4xl text-gray-400 mb-2">
              <i-ep-upload-filled />
            </el-icon>
            <div class="text-gray-600">
              <p>将文件拖拽到此处，或<em class="text-primary">点击上传</em></p>
              <p class="text-sm text-gray-500 mt-1">支持 .js, .ts, .jsonl, .json, .py 格式</p>
            </div>
          </div>
        </el-upload>
      </div>

      <!-- 格式选择 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          脚本格式
        </label>
        <el-radio-group v-model="currentFormat">
          <el-radio label="Playwright">Playwright (JavaScript/TypeScript)</el-radio>
          <el-radio label="JSONL">JSONL 格式</el-radio>
        </el-radio-group>
      </div>

      <!-- 解析预览区域 -->
      <div v-if="parsedSteps.length > 0" class="border-t pt-4">
        <h4 class="text-sm font-medium text-gray-700 mb-3">
          解析预览 ({{ parsedSteps.length }} 个步骤)
        </h4>
        <div class="max-h-60 overflow-y-auto space-y-2">
          <div
            v-for="(step, index) in parsedSteps"
            :key="index"
            class="flex items-center p-3 bg-gray-50 rounded-lg"
          >
            <div class="w-6 h-6 rounded-full bg-primary text-white flex items-center justify-center text-xs mr-3">
              {{ step.stepNumber || index + 1 }}
            </div>
            <el-icon class="mr-2 text-gray-600">
              <component :is="getStepIcon(step.type)" />
            </el-icon>
            <div class="flex-1">
              <div class="text-sm font-medium">{{ step.name || step.description }}</div>
              <div class="text-xs text-gray-500">{{ step.selector || step.url || step.details }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="parseError" class="bg-red-50 border border-red-200 rounded-md p-3">
        <div class="flex">
          <el-icon class="text-red-400 mr-2">
            <i-ep-warning />
          </el-icon>
          <div class="text-sm text-red-700">
            {{ parseError }}
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-between">
        <div>
          <el-button @click="parseScript" :disabled="!scriptContent.trim()">
            解析脚本
          </el-button>
          <el-button @click="convertFormat" :disabled="!scriptContent.trim()">
            转换格式
          </el-button>
        </div>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmImport"
            :disabled="parsedSteps.length === 0"
          >
            导入脚本 ({{ parsedSteps.length }} 个步骤)
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  UploadFilled as iEpUploadFilled,
  Warning as iEpWarning,
  Link as iEpLink,
  Edit as iEpEdit,
  Mouse as iEpMouse,
  View as iEpView,
  Clock as iEpClock,
  Camera as iEpCamera,
  Document as iEpDocument
} from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

// 响应式数据
const scriptContent = ref('')
const currentFormat = ref('Playwright')
const parsedSteps = ref([])
const parseError = ref('')
const uploadRef = ref()

// 计算属性
const updateVisible = (value) => emit('update:visible', value)

// 监听脚本内容变化，自动清除解析结果
watch(scriptContent, () => {
  parsedSteps.value = []
  parseError.value = ''
})

// 方法
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const resetForm = () => {
  scriptContent.value = ''
  currentFormat.value = 'Playwright'
  parsedSteps.value = []
  parseError.value = ''
}

const handleFileChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      scriptContent.value = e.target.result
      ElMessage.success('文件读取成功')
    } catch (error) {
      ElMessage.error('文件读取失败: ' + error.message)
    }
  }
  reader.readAsText(file.raw)
}

const parseScript = async () => {
  try {
    parseError.value = ''
    
    if (!scriptContent.value.trim()) {
      parseError.value = '请输入或上传脚本内容'
      return
    }

    // 使用脚本管理器进行导入
    const { scriptManager } = await import('../services/scriptManager.js')
    const result = scriptManager.importScript(scriptContent.value, currentFormat.value.toLowerCase())
    
    if (result.success) {
      parsedSteps.value = result.steps
      ElMessage.success(result.message)
      
      // 自动检测格式
      if (result.metadata && result.metadata.format) {
        currentFormat.value = result.metadata.format === 'playwright' ? 'Playwright' : 'JSONL'
      }
    } else {
      parseError.value = result.message
      parsedSteps.value = []
    }
  } catch (error) {
    console.error('解析脚本失败:', error)
    parseError.value = '脚本解析失败: ' + error.message
    parsedSteps.value = []
  }
}

const convertFormat = async () => {
  if (!scriptContent.value.trim()) {
    ElMessage.warning('请先输入脚本内容')
    return
  }

  try {
    // 使用格式转换器进行转换
    const { FormatConverter } = await import('../utils/formatConverter.js')
    
    // 检测当前格式
    const detectedFormat = FormatConverter.detectFormat(scriptContent.value)
    if (detectedFormat === 'unknown') {
      ElMessage.error('无法识别脚本格式')
      return
    }
    
    // 确定目标格式
    const targetFormat = currentFormat.value === 'Playwright' ? 'jsonl' : 'playwright'
    
    // 执行转换
    const convertedScript = FormatConverter.convertFormat(scriptContent.value, targetFormat)
    
    if (convertedScript.startsWith('//')) {
      // 转换失败，显示错误信息
      ElMessage.error('格式转换失败: ' + convertedScript.substring(2))
      return
    }
    
    // 更新脚本内容和格式
    scriptContent.value = convertedScript
    currentFormat.value = targetFormat === 'playwright' ? 'Playwright' : 'JSONL'
    
    ElMessage.success('格式转换成功')
    
    // 自动解析转换后的脚本
    await parseScript()
    
  } catch (error) {
    console.error('格式转换失败:', error)
    ElMessage.error('格式转换失败: ' + error.message)
  }
}

const confirmImport = async () => {
  if (parsedSteps.value.length === 0) {
    ElMessage.warning('请先解析脚本')
    return
  }

  try {
    // 触发导入确认事件
    emit('confirm', {
      content: scriptContent.value,
      format: currentFormat.value.toLowerCase(),
      steps: parsedSteps.value,
      metadata: {
        name: extractScriptName(scriptContent.value),
        importTime: new Date(),
        stepCount: parsedSteps.value.length
      }
    })

    ElMessage.success(`脚本导入成功！解析出 ${parsedSteps.value.length} 个步骤`)
    handleClose()
  } catch (error) {
    console.error('导入脚本失败:', error)
    ElMessage.error('导入脚本失败: ' + error.message)
  }
}

// 提取脚本名称
const extractScriptName = (content) => {
  const testNameMatch = content.match(/test\(['"]([^'"]+)['"],/)
  return testNameMatch ? testNameMatch[1] : 'imported_script'
}

// 获取步骤图标
const getStepIcon = (type) => {
  const iconMap = {
    'navigation': iEpLink,
    'input': iEpEdit,
    'click': iEpMouse,
    'assertion': iEpView,
    'wait': iEpClock,
    'screenshot': iEpCamera
  }
  return iconMap[type] || iEpDocument
}
</script>

<style scoped>
.el-textarea :deep(.el-textarea__inner) {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}
</style>